#!/usr/bin/python
# POLITEIA_LICENSE

import ogre.renderer.OGRE as ogre
import ogre.gui.CEGUI as CEGUI
import os

if os.name == 'nt':
    CEGUI.System.setDefaultXMLParserName('ExpatParser')
else:
    CEGUI.System.setDefaultXMLParserName('TinyXMLParser')
    
def cegui_reldim(x):
    return CEGUI.UDim((x), 0)
    
def cegui_vector2(x, y):
    return CEGUI.UVector2(cegui_reldim(x), cegui_reldim(y))
    
def cegui_color(x):
    return CEGUI.ColourRect(x,x,x,x)
    
class GraphicManager(object):
    CEGUISystem = None
    CEGUIRenderer = None
    def __init__(self, title, path, fullscreen=None):
        # TODO load config file
        self.Config = {}
        self.Config['Resolution'] = (1024, 768)
        self.Config['ResourceDir'] = os.path.join(path, 'media')
        self.Config['RenderSystem'] = ''
        self.Config['SceneManager'] = ogre.ST_GENERIC
        self.Config['Fullscreen'] = False
        # until here
        
        self.AnimationStates = {}
        self.AppTitle = title
        if fullscreen != None:
            self.Config['Fullscreen'] = fullscreen
        
        self.Root = ogre.Root()
        self._setup_resources(self.Config['ResourceDir'])
        self._init_render_window()
        self._setup_scene()
        self._init_cegui()
        
    def __del__(self):
        del self.CEGUISystem
        del self.CEGUIRenderer
        del self.Root
    
    def get_window_handler(self):
        return str(self.RenderWindow.getCustomAttributeInt('WINDOW'))
        
    def update(self, delta):
        self.Root._fireFrameStarted()
        self.RenderWindow.update()
        self.Root._fireFrameRenderingQueued()
        self.Root._fireFrameEnded()

        for anim in self.AnimationStates.keys():
            anim.addTime(delta * self.AnimationStates[anim])
    
    def add_animation_state(self, state, speed):
        self.AnimationStates[state] = speed
    
    def remove_animation_state(self, state):
        if self.AnimationStates.has_key(state):
            self.AnimationStates.pop(state)
        
    def _setup_resources(self, path):
        for root, lstDirs, lstFiles in os.walk(path):
            if ".svn" in lstDirs:
                lstDirs.remove('.svn')
            ogre.ResourceGroupManager.getSingleton().addResourceLocation(root,\
                    'FileSystem', 'General')
            for file in lstFiles:
                if file.lower().endswith('.zip'):
                    ogre.ResourceGroupManager.getSingleton().\
                            addResourceLocation(os.path.join(root, file), \
                                    'Zip', 'General')

    def _init_render_window(self):
        renderers = self.Root.getAvailableRenderers()

        if len(renderers) == 0:
            print "\n\nNO RENDERER AVAILABLE\n\n"
            sys.exit(-1)

        renderSystem = None
        for ren in renderers:
            if self.Config['RenderSystem'] == ren.getName():
                renderSystem = ren
        if renderSystem is None:
            renderSystem = renderers[0]
        self.Root.setRenderSystem(renderSystem)
        if self.Config['Fullscreen']:
            renderSystem.setConfigOption("Full Screen", "Yes")
        else:
            renderSystem.setConfigOption("Full Screen", "No")
        renderSystem.setLightingEnabled(True)
        renderSystem.setShadingType(ogre.SO_FLAT)

        renderSystem.setConfigOption("Video Mode", "%s x  %s" % \
                self.Config['Resolution'])
 
        self.RenderWindow = self.Root.initialise(True, self.AppTitle)
        ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
        ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()

    def _setup_scene(self):
        self.SceneManager = self.Root.createSceneManager(self.Config['SceneManager'], \
                "Default SceneManager")
        self.Camera = self.SceneManager.createCamera("Camera")
        viewport = self.Root.getAutoCreatedWindow().addViewport(self.Camera)
        self.Camera.setNearClipDistance(1.0)

    def _init_cegui(self):
        self.CEGUIRenderer = CEGUI.OgreCEGUIRenderer(self.RenderWindow,
                ogre.RenderQueueGroupID.RENDER_QUEUE_OVERLAY, False, 3000,
                self.SceneManager)
        self.CEGUISystem = CEGUI.System(self.CEGUIRenderer)
        CEGUI.Logger.getSingleton().loggingLevel = CEGUI.Insane

        CEGUI.SchemeManager.getSingleton().loadScheme("VanillaSkin.scheme")
        if not CEGUI.FontManager.getSingleton().isFontPresent("Commonwealth-10.font"):
            try:
                CEGUI.FontManager.getSingleton().createFont("Commonwealth-10.font")
            except:
                pass

        CEGUI.System.getSingleton().setDefaultMouseCursor("Vanilla-Images", "MouseArrow")
        CEGUI.System.getSingleton().setDefaultFont("Commonwealth-10")

        CEGUI.System.getSingleton().setGUISheet(
            CEGUI.WindowManager.getSingleton().loadWindowLayout("my.layout", False))
